package cn.com.darly.vpm.login;

import cn.com.darly.vpm.business.BusinessApi;
import cn.com.darly.vpm.business.friend.bean.FriendShip;
import cn.com.darly.vpm.framework.systemlog.resource.MessageResources;
import cn.com.darly.vpm.mobile.session.SessionUtil;
import cn.com.darly.vpm.security.BaseSecurityController;
import cn.com.darly.vpm.security.securitycfg.SecurityApi;
import cn.com.darly.vpm.security.securitycfg.UserDetials;
import cn.com.darly.vpm.security.user.api.LoginApi;
import cn.com.darly.vpm.security.user.bean.User;
import cn.com.darly.vpm.security.user.cfg.ApplicationConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @Author: Darly Fronch（张宇辉）
 * @Date：Create in 2017/9/12 18:40
 * @Modified By：Darly Fronch（张宇辉）
 * @Description：
 */
@Controller
public class LoginController extends BaseSecurityController {

    @Autowired
    LoginApi loginApi;

    @Resource
    BusinessApi businessApi;
    @Resource
    SecurityApi securityApi;

    @Resource
    MqttPahoMessageHandler mqtt;

    /**
     * 直接进入登录界面
     */
    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
    public String loginPage(String error, ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        hasUser(model);
        model.putAll(loginApi.login(error));
        return (String) model.get(ApplicationConst.getForwordUrl());
    }

    @RequestMapping({"/sameuser"})
    public String sameuser(ModelMap model) {
        model.putAll(loginApi.sameuser());
        return (String) model.get(ApplicationConst.getForwordUrl());
    }

    @RequestMapping({"/timeout"})
    public String timeout(ModelMap model) {
        hasUser(model);
        model.putAll(loginApi.timeout());
        return (String) model.get(ApplicationConst.getForwordUrl());
    }

    /***
     * 跳转到登陆页面
     */
    @RequestMapping(value = "/forwardLogin/", method = RequestMethod.GET)
    public String forwardLogin(ModelMap model) {
        hasUser(model);
        model.putAll(loginApi.forwardLogin());
        return (String) model.get(ApplicationConst.getForwordUrl());
    }
    /***
     * 项目入口，进入的页面
     */
    @RequestMapping(value = {"/index"}, method = RequestMethod.GET)
    public String index(ModelMap model, HttpServletRequest request) {
        UserDetials user = getCurrentUser();
        if (user == null) {
            model.addAttribute("hasUser", false);
            model.putAll(loginApi.index());//在这里定位入口。可以直接到登录页面，也可以到展示页面
            logger.info("[<方法index>没有登录用户]"+model.size());
            return (String) model.get(ApplicationConst.getForwordUrl());
        } else {
            logger.info("[<方法index>" + user.getAccount() + "]");
            return "redirect:/home";
        }
    }

    /***
     * 登錄后跳轉首頁
     */
    @RequestMapping(value = {"/home"}, method = RequestMethod.GET)
    public String home(ModelMap model, HttpServletRequest request) {

        boolean isRealse = this.isRealse(request.getSession().getServletContext());
        String resCode = null;
        if (isRealse) {
            MessageResources resource = MessageResources.getMessageInstance((String) null, (String) null, Locale.CHINA);
            resCode = resource.getMessage("res.code");
        }
        UserDetials user = getCurrentUser();
        if (user == null) {
            model.addAttribute("hasUser", false);
            logger.info("[<方法home>没有登录用户]");
            throw new UsernameNotFoundException("用户不存在");
        } else {
            logger.info("[<方法home>" + user.getAccount() + "]");
            model.addAttribute("user", user);
            model.addAttribute("role", user.getAuthorities());
            //获取登录用户的ID，根据id进行查询好友
            List<FriendShip> users =  businessApi.userFriend(user.getId());
            if (users != null&&users.size()>0){
                List<User> friendship= new ArrayList<User>();
                for (FriendShip ship:users) {
                    User friend = securityApi.findUserById(ship.getFriendid());
                    friendship.add(friend);
                }
                if (friendship!=null&&friendship.size()>0){
                    model.addAttribute("friendship",friendship);
                }
            }
            //登录后，给所有Android客户端发送通知
            for (String key:SessionUtil.SESSION_MAP.keySet()) {
                //获取用户登录信息
                User data = SessionUtil.SESSION_MAP.get(key);
                if (data==null) {
                    continue;
                }
                logger.info(data.getName()+"推送消息"+data.getDeviceId());
                Message<String> message = MessageBuilder.withPayload("-1#推送通知").setHeader(MqttHeaders.TOPIC, "vpm@"+data.getDeviceId()).build();
                mqtt.handleMessage(message);
            }
            model.putAll(loginApi.home());
            return (String) model.get(ApplicationConst.getForwordUrl());
        }
    }
}
